package com.atguigu.springcloud.controller;

import com.atguigu.springcloud.entities.CommonResult;
import com.atguigu.springcloud.entities.Payment;
import com.atguigu.springcloud.service.PaymentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.TimeUnit;

@RestController
@Slf4j
public class PaymentController {

    @Autowired
    private PaymentService paymentService;

    @Value("${server.port}")
    private String serverPort;

    @Resource
    private DiscoveryClient discoveryClient;

    @GetMapping(value = "/payment/get/{id}")
    public CommonResult getPaymentById(@PathVariable("id") long id){
        log.info("查询"+id);
        Payment payment= paymentService.getPaymentById(id);
        if(payment != null){
            return new CommonResult(200,"查询成功，sereverPort："+serverPort,payment);
        }else{
            return new CommonResult(444,"数据不存在，查询id："+id);
        }
    }

    @PostMapping(value = "/payment/create")
    public CommonResult create(@RequestBody  Payment payment){
        log.info(payment+"");
        int i = paymentService.create(payment);
        if(i > 0){
            return new CommonResult(200,"添加成功");
        }else{
            return new CommonResult(200,"添加失败");
        }
    }


    @GetMapping("/payment/getDiscover")
    public Object getDiscover(){
        List<String> services = discoveryClient.getServices();
        for(String service : services){
            log.info("****   element "+service);
            List<ServiceInstance> instances = discoveryClient.getInstances(service);
            for (ServiceInstance instance : instances){
                log.info(instance.getScheme()+" "+instance.getHost()+" "+instance.getServiceId());
            }

        }

        log.info("payment getDiscover 8001");

        return  discoveryClient;
    }

    @GetMapping("/payment/timeout")
     public String timeout(){
         try {
             TimeUnit.SECONDS.sleep(4);
         } catch (InterruptedException e) {
             e.printStackTrace();
         }
         return serverPort;
     }
}
